<?php
$jsStart = false;

/**
 * 页面中引入neditor
 * 例: {:ue_view()}
 * @param string $name 控件id及表单字段名称name,默认neditor,如果同一个页面多个neditor请分别设置不同id
 * @param string $content 编辑内容
 * @param array $config 配置项, 参考assets/neditor/neditor.config.js
 * @return string
 */
function ue_view(string $name = 'neditor', string $content = '', array $config = [], $no_js = false)
{
    $result = '';
    if (!$no_js) {
        global $jsStart;
        if (!$jsStart) {
            $result .= ue_js();
        }
    }
    $default = [
        "initialContent" => $content,
    ];
    $tconfig = new x_mier\neditor\config\Config();
    $config = array_merge($config, $tconfig->json()->getData());
    $config = array_merge($default, $config);
    $configJson = json_encode($config);
    $result .= '
        <script id="' . $name . '" name="' . $name . '" type="text/plain"></script>
        <script>
            UE.getEditor("' . $name . '",' . $configJson . ')
        </script>';
    return $result;
}

/**
 * 引入js
 *
 * @param string $version 版本号
 * @return string
 */
function ue_js(): string
{
    global $jsStart;
    $jsStart = true;
    return '
        <script type="text/javascript" charset="utf-8" src="/neditor/assets/neditor.config.min.js"></script>
        <script type="text/javascript" charset="utf-8" src="/neditor/assets/neditor.all.min.js"> </script>
        <script type="text/javascript" charset="utf-8" src="/neditor/assets/neditor.service.min.js"></script>
        <script type="text/javascript" charset="utf-8" src="/neditor/assets/i18n/zh-cn/zh-cn.js"></script>
        <script type="text/javascript" src="/neditor/assets/third-party/browser-md5-file.min.js"></script>
        <script type="text/javascript" src="/neditor/assets/third-party/jquery-1.10.2.min.js"></script>';
}

/**
 * neditor 设置
 *
 * @return string
 */
function ue_setting()
{
    return (new \x_mier\neditor\controller\Setting)->index();
}

/**
 * 路径拼接
 * 1.传入的多个参数用DIRECTORY_SEPARATOR连接
 * 2.将\\替换为/
 *
 * @param array ...$args
 * @return string
 */
function path_join(...$args): string
{
    $path = implode(DIRECTORY_SEPARATOR, $args);
    $path = path_fmt($path);
    return $path;
}

/**
 * 路径格式
 *
 * @param string $path
 * @return string
 */
function path_fmt($path)
{
    $path = str_replace('//', '/', $path);
    $path = str_replace('\\', '/', $path);
    return $path;
}

/**
 * 验证session中是否有uid
 * @return bool 验证结果
 */
function check_uid()
{
    $config = new \x_mier\neditor\config\Config();
    $uid = $config->get('session_uid_key', 'uid');
    if (session($uid)) {
        return true;
    }
    return false;
}
